package repository.impl;

import java.util.List;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import repository.UserRepository;
import domain.User;
import domain.exceptions.DuplicateException;
import domain.exceptions.DuplicateException.DupErrorCode;


@Repository
public class UserRepositoryImpl extends AbstractHibernateRepository<User> implements UserRepository{

	@Autowired
	public UserRepositoryImpl(SessionFactory sessionfactory){
		super(sessionfactory);
	}
	
	public User validate(String docnumber, String password) {
		String hql = "FROM User WHERE docnumber=? AND password=?";
		List<User> result = find(hql, docnumber, password);
		return result.isEmpty() ? null : result.get(0);
	}

	public User getUser(int id) {
		return get(User.class, id);
	}
	
	public User getUserByDocNumber(String docnumber) {
		String hql = "FROM User WHERE docnumber=?";
		List<User> result = find(hql, docnumber);
		return result.isEmpty() ? null : result.get(0);
	}
	
	public User getUserByEmail(String email) {
		String hql = "FROM User WHERE email=?";
		List<User> result = find(hql, email);
		return result.isEmpty() ? null : result.get(0);
	}
	
	public User getUser(String docnumber, String email) {
		String hql = "FROM User WHERE docnumber=? AND email=?";
		
		List<User> result = find(hql, docnumber, email);
		return result.isEmpty() ? null : result.get(0);
	}
	
	public void newUser(User user)throws DuplicateException{
		if (getUserByDocNumber(user.getDocNumber()) != null) {
			throw new DuplicateException(DupErrorCode.DUP_DOC_NUMBER);
		} else if (getUserByEmail(user.getEmail()) != null) {
			throw new DuplicateException(DupErrorCode.DUP_EMAIL);
		}
		save(user);
	}

	@Override
	public List<User> getRegisteredUsers() {
		String hql = "FROM User WHERE admin=1 ORDER BY lastaccess DESC";
		return find(hql);		
	}
	
	public void deleteUser(User user){
		delete(user);
	}

	@Override
	public List<User> getPendingUserRequests() {
		String hql = "FROM User WHERE admin=0 and confirmed=0";
		return find(hql);
	}
}